package com.linko.intelligent.remote.core.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linko.intelligent.common.util.HttpUtil;
import com.linko.intelligent.remote.core.mapper.CategoryMapper;
import com.linko.intelligent.remote.core.service.CategoryRefreshService;
import com.linko.intelligent.remote.pojo.dto.CategoryDto;
import com.linko.intelligent.remote.pojo.po.Category;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class CategoryRefreshServiceImpl implements CategoryRefreshService {
    private static final Logger logger = LoggerFactory.getLogger(CategoryRefreshServiceImpl.class);

    @Value("${url.dj82}")
    private String apiUrl;

    @Value("${url.authorization}")
    private String authorization;

    @Autowired
    private CategoryMapper categoryMapper;

    public void refresh() {
        // 获取请求头
        HashMap<String, String> requestHeader = new HashMap<>();
        requestHeader.put("Authorization", authorization);

        // 发送 POST 请求并获取响应
        try (Response response = HttpUtil.get(apiUrl + "/config/category/list", requestHeader)) {
            // 处理响应
            handleResponse(response);
        }
    }

    private void handleResponse(Response response) {
        if (response != null && response.isSuccessful()) {
            try {
                String responseBody = response.body().string();
                JSONObject jsonResponse = JSONObject.parseObject(responseBody);
                JSONArray listArray = jsonResponse.getJSONArray("data");
                // 解析并处理响应数据
                List<CategoryDto> categoryDtoList = parseAndProcessResponse(listArray);
                // 记录成功信息
                logger.info("成功解析并处理响应数据");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            logger.error("请求失败");
        }
    }

    private List<CategoryDto> parseAndProcessResponse(JSONArray listArray) {
        // 创建列表存储设备信息
        List<CategoryDto> categoryDtoList = new ArrayList<>();
        for (int i = 0; i < listArray.size(); i++) {
            JSONObject jsonObject = listArray.getJSONObject(i);
            // 将 JSON 对象转换为 CategoryDto 对象
            CategoryDto categoryDto = jsonObject.toJavaObject(CategoryDto.class);
            categoryDtoList.add(categoryDto);
        }
        // 清空现有数据
        categoryMapper.deleteAll();
        // 插入新数据
        List<Category> categoryList = new ArrayList<>();
        for (CategoryDto dto : categoryDtoList) {
            Category category = new Category();
            BeanUtils.copyProperties(dto, category);
            categoryList.add(category);
        }
        categoryMapper.batchInsert(categoryList);
        return categoryDtoList;
    }
}
